<script>
  import axios from 'axios'
  //引入时间戳转换函数
  import {formatDate} from "../../../common/common";
  //引入http的方法
  import {readingcheck,readingupdate, readingmess,readingfiles,readingadd} from '@/api/readingmanagement/reading'
  import {teachername} from '@/api/slider/slider'
  export default {
    //跟读编辑页面名
    name: "ReadingEdit",
    props:{
      upload:String
    },
    data() {
      return {
        //设置上线时间为今日和今日以后的时间
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() < Date.now()-8.64e7;
          }
        },
        //设置loading图，当http请求结束后设为false
        loading:true,
        saved:false,
        //select选择器
        options: [],
        //路由跳转传参获取id
        index: '',
        //页面的主要数据
        tableData: {
          //封面图片
          imageUrl: '',
          //上线日期value
          upload: '',
          // value1:'',
        },
        rules:{
          title:[
            { required: true, message: '请输入跟读标题', trigger: 'blur' },
            { min: 1, max: 10, message: '标题不宜过长,控制在10个字以内哦', trigger: 'blur' }
          ],
          message:[
            { required: true, message: '请填写对学生的寄语', trigger: 'blur' },
          ],
          upload:[
            { required: true, message: '请选择上线日期', trigger: 'blur' },
          ]
        }
      }
    },
    beforeRouteLeave (to, from, next) {
      if (this.saved || window.confirm('您还没有更新,是否返回?')) {
        next()
      } else {
        next(false)
      }
    },
    methods: {
      //图片上传成功之后的回调函数
      handleAvatarSuccess(res) {
        this.tableData.nameImg = '';
        this.tableData.imageUrl = res.URLList[0].url;
      },
      //删除行
      handledel(index) {
        if (this.tableData.messList.length < 7) {
          alert("您最少需要6行")
        } else {
          this.tableData.messList.splice(index, 1)
        }
      },
      //添加行
      insert(index) {
        if (this.tableData.messList.length > 9) {
          alert("最多10行")
        } else {
          this.tableData.messList.splice(index + 1, 0, {
            mess: '',
            messCN: '',
            messEN: '',
            flag: false,
            id: '',
            edit: false,
            key: Date.now()
          });
        }
      },
      //音频播放
      handleaudio(row, index) {
        var play = document.getElementsByTagName('audio');
        for (var i = 0; i < this.tableData.messList.length; i++) {
          if (i == index) {
            if (!row.flag) {
              play[i].play();
              row.flag = true;
            } else {
              play[i].pause();
              row.flag = false;
            }
          } else {
            play[i].pause();
            this.tableData.messList[i].flag = false;
          }
        }
      },
      handleinput(row){
        var pattern=/^[%&',，。·~;=?\u4e00-\u9fa5\s]+$/;
        if(!pattern.test(row)){
          this.$message.error('错了哦，这里输入中文');
        }
        if(row.length==0){
          this.$message.error('不能为空哦');
        }
        if(row.length>20){
          this.$message.error('内容太长了,分行来写吧');
        }
      },
      handleEN(row){
        var pattern=/^[%&'’,.;=?A-Za-z\s]+$/;
        if(!pattern.test(row)){
          this.$message.error('错了哦，这里输入英文');
        }
        if(row.length==0){
          this.$message.error('不能为空哦');
        }
        if(row.length>50){
          this.$message.error('内容太长了,分行来写吧');
        }
      },
      //音频上传之前的回调函数
      beforeupload1(file) {
        let id="1"+this.index;
        localStorage.setItem(id,file.name);
        const isLt2M = file.size / 1024 / 1024 < 10;
        console.log(file.size / 1024 / 1024);
        const isMP3 = file.type === 'audio/mp3';
        if (!isLt2M) {
          this.$message.error('上传音频最好不要超过10MB哦，您可以多读几条分开上传');
          return isLt2M;
        }
        if (!isMP3) {
          this.$message.error('请上传音频格式的文件哦');
          return isMP3;
        }
        return isLt2M && isMP3
      },
      //音频上传成功之后的回调函数
      handleAudioSuccess(response) {
        console.log(response);
        for (let i = 0; i < this.tableData.messList.length; i++) {
          if (localStorage.getItem("1"+i) !== null && localStorage.getItem("1"+i) == response.fileName) {
            this.tableData.messList[i].mess = response.URLList[0].url
          }
        }
        // this.tableData.messList[this.index].mess = response.URLList[0].url;
      },
      //选中行的index
      handleindex(row, index,column) {
        this.index = index;
      },
      //获取选中id的数据
      getDetailInfo() {
        localStorage.teacherindex = this.$route.params.index === undefined ? localStorage.teacherindex : this.$route.params.index;
        let id = localStorage.teacherindex;
        readingcheck(id).then(this.reading);
      },
      //渲染页面
      reading(res) {
        for (let i = 0; i < res.data.messList.length; i++) {
          res.data.messList[i].flag = false;
          res.data.messList[i].edit = false;
          res.data.readBelong='';
        }
        this.loading=false;
        this.tableData = res.data;
        for(let i=0;i<10;i++){
          localStorage.removeItem("1"+i)
        }
        this.handleslider();
      },
      //返回上一层
      goback() {
        for(let i=0;i<10;i++){
          localStorage.removeItem("1"+i)
        }
        this.$router.push({
          path: '/1'
        })
      },
      //删除当前行的内容
      handleDel(index,row){
        console.log(index);
        console.log(row);
        row.mess='';
        row.messCN='';
        row.messEN='';
      },
      //获取上传formdata之后返回的id
      handlefiles(res){
        for (let item of res.data.messlist) {
          this.tableData.readBelong += item.id + ','
        }
        return this.tableData.readBelong;
      },
      //上传跟读编辑的内容
      handleupload(res){
        let params={};
        params.readBelong=res;
        params.createBy=this.tableData.createBy;
        params.title=this.tableData.title;
        params.nameImg=this.tableData.nameImg?this.tableData.nameImg:this.tableData.imageUrl;
        params.message=this.tableData.message;
        params.state=this.tableData.state;
        params.uploadTime=this.tableData.upload.valueOf();
        let _this=this;
        let id=localStorage.teacherindex;
        readingupdate(id,params).then(function (res) {
          console.log(res);
          if(res.data.code==2){
            _this.$message.error('时间线有冲突请重新重新选择发布日期');
            for (let i = 0; i < 10; i++) {
              localStorage.removeItem("1"+i)
            }
          } else{
            _this.$confirm('确定修改跟读任务吗', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              _this.$message({
                type: 'success',
                message: '已提交跟读任务!'
              });
              _this.saved=true;
              for(let i=0;i<10;i++){
                localStorage.removeItem("1"+i)
              }
              _this.$router.push({name: 'ReadingManagement'})
            }).catch(() => {
              _this.$message({
                type: 'info',
                message: '已取消更新'
              });
            });
          }
        })
      },
      timechange(val){
        let date=new Date();
        if(this.$moment(val.valueOf()).format("D")==date.getDate()){
          this.tableData.state="1"
        }else {
          this.tableData.state="2"
        }
        console.log(this.tableData.state);
      },
      //点击提交之后执行的方法
      handlesub(tableData) {
        let _this=this;
        this.$refs[tableData].validate((valid) => {
          if (valid) {
            let mess = [];
            for (let item of _this.tableData.messList) {
              mess.push({
                messCN: item.messCN,
                messEN: item.messEN,
                mess: item.mess
              })
            }
            for(let i=0;i<10;i++){
              localStorage.removeItem("1"+i)
            }
            let time=this.tableData.upload.valueOf();
            readingfiles(JSON.stringify(mess),time).then(_this.handlefiles).then(_this.handleupload);
          } else {
            this.$message.error('内容填写不完整');
            return false;
          }
        });
      },
      //下拉菜单(老师）的内容渲染
      handleslider(){
        let _this=this;
        teachername().then(function (res) {
          if(res.status==200){
            for(let item of res.data.UserList){
              _this.options.push({
                value:item.id,
                label:item.name+'老师,Id'+item.id
              })
            }
          }
        })
      },
    },
    //页面刚进入的时候请求一个单页面的数据
    created() {
      this.getDetailInfo();
    }
  }
</script>
<template>
  <div class="wrapper">
    <el-breadcrumb separator="/" class="title">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{path:'/1'}">跟读管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{path:'/1'}">跟读列表</el-breadcrumb-item>
        <el-breadcrumb-item>跟读编辑</el-breadcrumb-item>
      </el-breadcrumb>
    </el-breadcrumb>
    <div class="content">
      <el-form label-width="100px" :model="tableData" ref="tableData" :rules="rules">
        <el-form-item label="标题" class="form" prop="title">
          <el-input v-model="tableData.title"></el-input>
        </el-form-item>
        <el-form-item label="封面图片">
          <img v-if="tableData.nameImg" :src="tableData.nameImg" alt="">
          <el-upload
            :action="upload"
            name="files"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="tableData.imageUrl" :src="tableData.imageUrl" class="avatar">
            <el-button type="primary" class="update">点我更新</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="跟读内容">
          <el-table :data="tableData.messList" style="width: 100%"  v-loading="loading">
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column label="英文" width="240">
              <template slot-scope="scope">
                <el-input v-show="scope.row.edit" size="small" v-model="scope.row.messEN" @change="handleEN(scope.row.messEN)"></el-input>
                <span v-show="!scope.row.edit">{{ scope.row.messEN }}</span>
              </template>
            </el-table-column>
            <el-table-column label="中文" width="240">
              <template slot-scope="scope">
                <el-input v-show="scope.row.edit" size="small" v-model="scope.row.messCN" @change="handleinput(scope.row.messCN)"></el-input>
                <span v-show="!scope.row.edit">{{scope.row.messCN}}</span>
              </template>
            </el-table-column>
            <el-table-column label="跟读录音" width="280" class="oper">
              <template slot-scope="scope">
                <el-upload
                  :action="upload"
                  name="files"
                  :before-upload="beforeupload1"
                  :on-success="handleAudioSuccess">
                  <el-button size="small" :type="scope.row.mess?'danger':'primary'"
                             @click="handleindex(scope.row,scope.$index,scope.column)">
                    {{scope.row.mess?'已上传':'上传文件'}}
                  </el-button>
                </el-upload>
                <el-button @click="handleaudio(scope.row,scope.$index)" :type="scope.row.flag?'danger':'primary'">
                  {{scope.row.flag?'暂停':'播放'}}
                </el-button>
                <el-button type="info" @click="handleDel(scope.$index,scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column width="100" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="handledel(scope.$index)" style="color:red">删除行</el-button>
                <el-button type="text" @click="insert(scope.$index)">插入行</el-button>
              </template>
            </el-table-column>
            <el-table-column width="80" label="编辑" class="edit">
              <template slot-scope="scope">
                <el-button v-show='!scope.row.edit' type="primary" icon="el-icon-edit" @click="scope.row.edit=true">编辑
                </el-button>
                <el-button v-show='scope.row.edit' type="success" icon="el-icon-check" @click="scope.row.edit=false">
                  完成
                </el-button>
              </template>
            </el-table-column>
            <el-table-column width="0">
              <template slot-scope="scope">
                <audio :src="scope.row.mess"></audio>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="发布老师">
          <el-select v-model="tableData.createBy" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="老师寄语" prop="message">
          <el-input v-model="tableData.message"></el-input>
        </el-form-item>
        <el-form-item label="上线日期" prop="upload">
          <el-date-picker class="setuptime"
                          v-model="tableData.upload"
                          type="date"
                          :picker-options="pickerOptions1"
                          @change="timechange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="goback">返回</el-button>
          <el-button type="success" @click="handlesub('tableData')">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style lang="less" scoped>
  @import "~styles/z.less";
  @import "~styles/css3.less";
  @import "~styles/variables.less";

  .wrapper {
    .w100;
  }

  /deep/ .cell {
    display: flex;
    justify-content: space-around;
    width: 100%;
    button {
      width: 60px;
      height: 30px;
      justify-content: center;
      display: flex;
      align-items: center;
    }
  }
  .avatar-uploader /deep/ .el-upload {
    border: 5px dashed lightgrey;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/ .el-table__row{
    height:100px;
  }
  /deep/ .el-upload-list__item{
    .abs;
  }
  /deep/ th{
    text-align: center;
    display:table-cell;
    vertical-align:middle;
    /deep/ .cell{
      height:100px;
      display: flex;
      align-items: center;
    }
  }
  /deep/ .cell{
    height:100px;
    display: flex;
    align-items: center;
  }
  .avatar-uploader /deep/ .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  img {
    width: 150px;
    height: 150px;
  }
  /deep/ .el-input__inner {
    height: 43px;
    font-size: 13px;
    width: 300px;
  }
</style>
